<template>
  <view class="pay u-p-b-83">
      <!-- 地址栏 -->
      <view class="address-item">
          <!-- 按钮 -->
          <view class="address-item-btn u-text-center u-p-30" v-if="!address" >
              <u-button 
              @click="handleChooseAddress"
              plain
              shape="circle"
              type="error"
              size="medium"
              >选择地址</u-button>
          </view>
          <!-- 有地址显示地址信息 -->
          <view class="address-item-message u-p-30" v-else >
              <!-- 地址信息 -->
              <view class="address-info">{{detailAddress}}</view>
              <!-- 用户信息 -->
              <view class="user-info u-p-t-20 u-flex" >
                  <!-- 名字 -->
                  <text class="name u-m-r-20">{{address.userName}}</text>
                  <!-- 电话 -->
                  <text>{{address.telNumber}}</text>
              </view>
          </view>
      </view>
      <u-line color="#eee"></u-line>
      <u-line color="#eee"></u-line>
      <u-line color="#eee"></u-line>
      <u-line color="#eee"></u-line>

      <!-- 商品栏 -->
      <view class="checked-list">
          <!-- 标题 -->
          <view class="checked-list-title u-p-20">已选商品</view>
          <view class="checked-list-item u-p-20">
               <u-swipe-action   
			v-for="(item,index) in checkedList" :key="item.goods_id"
      :index="index"
      :show="item.show"
			:options="options"
      btn-width="180"
		>
               <view class="cart-item">
        <!-- 图片 -->
        <view class="cart-img">
          <u-image width="191rpx" height="191rpx" :src="item.goods_small_logo"></u-image>
        </view>
        <view class="title-wrap">
					 <!-- 商品信息 -->
        <view class="cart-info">
          <view class="cart-info-name u-line-2">{{item.goods_name}}</view>
          <!-- 信息工具 -->
          <view class="cart-info-tool">
            <!-- 价格 -->
            <view class="cart-info-tool-price">￥{{item.goods_price}}</view>
            <!-- 数量加减 -->
            <view class="cart-info-tool-count">
              <view class="count">x{{item.num}}</view>
            </view>
          </view>
        </view>
				</view>
       
      </view>
       </u-swipe-action>
          </view>
      </view>

      <!-- 支付栏 -->
      <view class="statistics  u-p-30">
      <!-- 合计 -->
      <view class="total">
        合计:
        <text class="rmb">￥</text>
        <!-- 价格 -->
        <text class="price">{{totalPrice}}</text>
      </view>
      <!-- 结算按钮 -->
      <u-button @click="hangdlePay" type="error" :custom-style="{fontSize:'26rpx',width:'220rpx',height:'52rpx',borderRadius:'26rpx'}">去支付({{totalNum}})</u-button>
    </view>
  </view>
</template>

<script>
import {mapGetters ,mapMutations, mapState,mapActions} from 'vuex'
export default {
    data(){
        return{
        // address:null,
        btnWidth: 180,
      show:false,
      disabled:false,
      options: [
					{
						text: '删除',
						style: {
							backgroundColor: '#dd524d'
						}
					}
				]
        }
    },
    computed:{
        ...mapState(['token']),
        // 获取数据列表渲染
        ...mapGetters(['checkedList','totalPrice','totalNum','address']),

        // 用户地址
        detailAddress(){
            if(!this.address) return ""
            const {provinceName,cityName,countyName,detailInfo} = this.address
            return provinceName+cityName+countyName+detailInfo
        }
    },
    // async onLoad(){
    //     const [err,res] = await uni.getStorageSync('address')
    //     this.address = res
    // },
    methods:{
        // 调用vuexmutation方法
        ...mapMutations(['setAddress']),
        ...mapActions(['fetchToken']),
        // 点击获取收货地址
       async handleChooseAddress(){
            // 调用api接口
            const [err,address] = await uni.chooseAddress()
            console.log(43,address);
            // this.address = result
            this.setAddress(address)
            // uni.setStorageSync('address', result)
        },

        //  // 滑动删除
        // click(index, index1) {
        //   console.log(180,index, index1);
		// 		if(index1 == 0) {
		// 			this.cartList.splice(index, 1);
		// 			this.$u.toast(`删除了第${index}个cell`);
        //   this.$store.commit('setCartList',this.cartList)
		// 		} 
        // // else {
		// 		// 	this.cartList[index].show = false;
		// 		// 	this.$u.toast(`收藏成功`);
		// 		// }
		// 	},
		// 	// 如果打开一个的时候，不需要关闭其他，则无需实现本方法
		// 	open(index) {
		// 		// 先将正在被操作的swipeAction标记为打开状态，否则由于props的特性限制，
		// 		// 原本为'false'，再次设置为'false'会无效
		// 		this.cartList[index].show = true;
		// 		this.cartList.map((val, idx) => {
		// 			if(index != idx) this.cartList[idx].show = false;
		// 		})
		// 	},


        // 点击去支付
        async hangdlePay(){
            // 判断是否有收货地址
            if(!this.address){
                // 没有就提示
                uni.showToast({
                    title:'您还没选择收货地址',
                    icon:'none'
                })
                return
            }
            
            // 有就跑微信支付流程

            // // 1.调用api获取到拿token所需要的前四个参数
            // const [err1,{ encryptedData, rawData, iv, signature }] = await uni.getUserInfo({
            //     desc:'方便用户'
            // })
            // // console.log(166,res1);

            // const [err2,{code}] = await  uni.login()
            // // console.log(171,code);


            // // 获取token需要的参数值，放到一个对象中
            // const tokenParams = {
            //     encryptedData,
            //     rawData,
            //     iv,
            //     signature,
            //     code,
            // }


            // // 发起请求获取token
            // const res3 = await this.$u.post('/users/wxlogin',tokenParams)
            // // console.log(185,res3);
            // const {token} = res3.message
                    if(!this.token){
                     await this.fetchToken()
                       
                    }
            // 创建订单环节
            // 1.获取到创建订单接口所需要的参数
            const orderParams = {
                // 订单总价格
                order_price:this.totalPrice,
                // 订单地址
                consignee_addr:this.detailAddress+'-'+this.address.userName+'-'+this.address.telNumber,
                // 订单数组
                goods:this.checkedList.map((item)=>({
                    goods_id:item.goods_id,
                    goods_number:item.num,
                    goods_price:item.goods_price
                })
                )
            }


            // 2.发起请求创建订单
            const res4 = await this.$u.post('/my/orders/create',orderParams)
            // console.log(209,res4);
            // 获取支付参数
            const {order_number} = res4.message


            // 通过订单号获取支付参数
            const res5 = await this.$u.post('/my/orders/req_unifiedorder',{order_number})
            // console.log(res5);

            // 获取支付参数
            const {pay} = res5.message


            // 通过支付参数调用微信支付
            const res6 = await uni.requestPayment(pay)

              // 查询当前订单 是否已经支付
      const res7 = await this.$u.post(
        "/my/orders/chkOrder",
        { order_number }
      );
      console.log(res7);
      if(res7.message === '支付成功'){
         // 是  提示用户 或者跳转页面 跳转订单页面。。。
         uni.showToast({
             title:'支付成功',
             icon:'none'
         })
      }else{
          uni.showToast({
             title:'支付失败',
             icon:'error'
         })
      }
      
         
      // 失败。。。提
        }

    }
}
</script>

<style lang="scss">
 .cart-item {
   display: flex;
   padding: 20rpx 25rpx;

    .cart-check {
     flex: 1;
     display: flex;
     justify-content: center;
     align-items: center;
    }

    .cart-img {
     flex: 2;
     display: flex;
     justify-content: center;
     align-items: center;
    }
.title-wrap{
   .cart-info {
      flex: 3;
      margin-left: 10rpx;
      margin-right: 20rpx;
      display: flex;
      flex-direction: column;
      justify-content: space-around;
      .cart-info-name{
        margin-bottom: 20rpx;
      }
      .cart-info-tool {
        display: flex;
        justify-content: space-between;
        .cart-info-tool-price {
        color: $themeColor;
        }

        .cart-info-tool-count {
          display: flex;
          color: #666;
          .btn {
            width: 32rpx;
            height: 32rpx;
            border: 1px solid #000;
            display: flex;
            justify-content: center;
            align-items: center;
            border-radius: 50%;
          }

          .count {
                margin: 0 20rpx;
          }
        }
      }
    }
}
   
  }

  // 统计栏样式
.statistics {
 height: 83rpx;
  position: fixed;
  width: 100%;
  bottom: 0;
  left: 0;
  border-top: 1rpx solid #ccc;
  display: flex;
  padding: 0 10rpx;
  align-items: center;
  .all-chk {
  padding: 0 10rpx;
  }

  .total {
    flex: 1;
    .rmb {
color: $themeColor;
      font-size: 20rpx;
    }

   
    .price {
color: $themeColor;
    }
  }
}
</style>